import java.util.Arrays;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * user:likai
 * Date:2022-12-08
 * Time:12:02
 */
class MyBlockingQueue{
    //循环队列
    private int elem[]=new int[100];
    private volatile int size;
    private volatile int head;
    private volatile int tail;
    public void put(int cur) throws InterruptedException {
        //判断是不是满了
        synchronized (this){
            while(size>=elem.length){
                this.wait();
            }
            elem[tail]=cur;
            tail++;
            size++;
            if(tail==elem.length){
                tail=0;
            }
            this.notify();
        }
    }
    public Integer take() throws InterruptedException {
        synchronized (this){
            //判断空
            while(size==0){
                this.wait();
            }
            int ret=elem[head];
            head++;
            size--;
            if(head== elem.length){
                head=0;
            }
            this.notify();
            return ret;
        }
    }
}
public class Test {
    public static void main1(String[] args) throws InterruptedException {
        BlockingQueue<Integer> blockingQueue = new LinkedBlockingQueue<>();
        blockingQueue.put(1);
        System.out.println(blockingQueue.take());
    }

    public static void main(String[] args){
        MyBlockingQueue queue=new MyBlockingQueue();
        Thread thread1=new Thread(()->{
            int i=1;
            while(true){
                try {
                    Thread.sleep(500);
                    queue.put(i);
                    System.out.println("输入："+i);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                i++;
            }
        });
        Thread thread2=new Thread(()->{
            while (true){
                try {
                    Thread.sleep(1000);
                    int n=queue.take();
                    System.out.println("输出："+n);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        thread1.start();
        thread2.start();
    }
}
